import java.util.LinkedList;
import java.util.Queue;

/**
 * @author SongJun
 * @description 二叉树最大深度(BFS)
 * @date 2021/9/9 16:24
 */
public class Leetcode104 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }

    public static void main(String[] args) {
        TreeNode c1 = new TreeNode(20);
        c1.left = new TreeNode(15);
        c1.right = new TreeNode(7);
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = c1;

        Leetcode104 instance = new Leetcode104();
        System.out.println(instance.maxDepth(root));
    }

    public int maxDepth(TreeNode root) {
        if(root == null){
            return 0;
        }
        int ret = 1;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int step = 1;
        while (!queue.isEmpty()){
            int curSize = queue.size();
            for(int i=0; i<curSize; i++){
                TreeNode node = queue.poll();
                if(node == null){
                    continue;
                }
                if(node.left == null && node.right == null){
                    ret = Math.max(ret, step);
                }
                if(node.left != null){
                    queue.offer(node.left);
                }
                if(node.right != null){
                    queue.offer(node.right);
                }
            }
            step++;
        }
        return ret;
    }
}
